'use strict';

const Controller = require('egg').Controller;

class RecommendationController extends Controller {

  // 获取天气信息
  async getWeatherInfo() {
    const { ctx, service } = this;

    try {
      const { city, lat, lng } = ctx.query;

      let targetCity = city;

      // 如果没有指定城市但提供了坐标，进行逆地理编码
      if (!city && lat && lng) {
        try {
          const location = await service.location.reverseGeocode(parseFloat(lat), parseFloat(lng));
          targetCity = location.city;
        } catch (error) {
          console.log('逆地理编码失败，使用默认城市');
          targetCity = '北京';
        }
      }

      // 如果都没有提供，尝试IP定位
      if (!targetCity) {
        try {
          const ip = ctx.request.ip || ctx.ip;
          const location = await service.location.getLocationByIP(ip);
          targetCity = location.city;
        } catch (error) {
          console.log('IP定位失败，使用默认城市');
          targetCity = '北京';
        }
      }
console.log('使用默认城市',city,lat,targetCity)
      const weather = await service.recommendation.getWeatherInfo(targetCity || '北京');

      ctx.body = {
        code: 200,
        message: '获取天气信息成功',
        data: weather
      };
    } catch (error) {
      console.error('获取天气信息失败:', error);
      ctx.throw(500, '获取天气信息失败，请稍后重试');
    }
  }

  // 获取智能推荐
  async getSmartRecommendations() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;

    try {
      const { city, lat, lng, occasion, includeWeather = 'true', useAI = 'true' } = ctx.query;

      // 获取用户位置信息
      let locationInfo = null;

      if (lat && lng) {
        // 使用提供的坐标进行逆地理编码
        try {
          locationInfo = await service.location.reverseGeocode(parseFloat(lat), parseFloat(lng));
        } catch (error) {
          console.log('逆地理编码失败');
        }
      } else if (city) {
        // 使用提供的城市名进行地理编码
        try {
          locationInfo = await service.location.geocode(city);
        } catch (error) {
          console.log('地理编码失败');
        }
      }

      // 如果都没有，尝试IP定位
      if (!locationInfo) {
        try {
          const ip = ctx.request.ip || ctx.ip;
          locationInfo = await service.location.getLocationByIP(ip);
        } catch (error) {
          console.log('IP定位失败，使用默认位置');
          locationInfo = service.location.getDefaultLocation();
        }
      }

      const recommendations = await service.recommendation.getSmartRecommendations(userId, {
        locationInfo,
        occasion,
        includeWeather: includeWeather === 'true',
        useAI: useAI === 'true'
      });

      ctx.body = {
        code: 200,
        message: '获取推荐成功',
        data: recommendations
      };
    } catch (error) {
      console.error('获取智能推荐失败:', error);
      ctx.throw(500, '获取推荐失败，请稍后重试');
    }
  }

  // AI风格分析
  async getAIStyleAnalysis() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;

    try {
      // 获取用户穿搭历史
      const wearHistory = await ctx.model.WearRecord.findAll({
        where: { user_id: userId },
        include: [{
          model: ctx.model.Outfit,
          as: 'outfit'
        }],
        order: [['created_at', 'DESC']],
        limit: 30
      });

      // 获取用户衣服
      const clothingItems = await ctx.model.Clothing.findAll({
        where: { user_id: userId },
        include: [{
          model: ctx.model.Category,
          as: 'category'
        }]
      });

      // AI分析
      const analysis = await service.aiAnalysis.analyzePersonalStyle(wearHistory, clothingItems);

      ctx.body = {
        code: 200,
        message: 'AI风格分析完成',
        data: {
          analysis,
          wearHistoryCount: wearHistory.length,
          clothingCount: clothingItems.length
        }
      };
    } catch (error) {
      console.error('AI风格分析失败:', error);
      ctx.throw(500, 'AI分析失败，请稍后重试');
    }
  }

  // 检查AI服务状态
  async checkAIStatus() {
    const { ctx, service } = this;

    try {
      const config = service.aiAnalysis.getAIConfig();
      const status = {
        provider: config.provider,
        available: false,
        message: '',
        services: {}
      };

      // 检查各个AI服务的可用性
      const services = ['local', 'qianwen', 'deepseek', 'doubao', 'vapi'];

      for (const serviceName of services) {
        try {
          if (serviceName === 'local') {
            status.services[serviceName] = { available: true, message: '本地AI引擎可用' };
          } else {
            // 检查API密钥是否配置
            const keyMap = {
              qianwen: config.qianwenApiKey,
              deepseek: config.deepseekApiKey,
              doubao: config.doubaoApiKey,
              vapi: config.vapiKey
            };

            const apiKey = keyMap[serviceName];
            if (apiKey && apiKey !== `your_${serviceName}_key`) {
              status.services[serviceName] = { available: true, message: 'API密钥已配置' };
            } else {
              status.services[serviceName] = { available: false, message: 'API密钥未配置' };
            }
          }
        } catch (error) {
          status.services[serviceName] = { available: false, message: error.message };
        }
      }

      // 设置总体状态
      status.available = status.services[config.provider]?.available || false;
      status.message = status.services[config.provider]?.message || '服务不可用';

      ctx.body = {
        code: 200,
        message: 'AI服务状态检查完成',
        data: status
      };
    } catch (error) {
      console.error('AI服务状态检查失败:', error);
      ctx.body = {
        code: 500,
        message: 'AI服务状态检查失败',
        data: {
          provider: 'unknown',
          available: false,
          message: error.message,
          services: {}
        }
      };
    }
  }

  // 获取今日推荐
  async getTodayRecommendations() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;

    try {
      const { city, lat, lng } = ctx.query;

      // 获取用户位置信息
      let locationInfo = null;

      if (lat && lng) {
        // 使用提供的坐标进行逆地理编码
        try {
          locationInfo = await service.location.reverseGeocode(parseFloat(lat), parseFloat(lng));
        } catch (error) {
          console.log('逆地理编码失败');
        }
      } else if (city) {
        // 使用提供的城市名进行地理编码
        try {
          locationInfo = await service.location.geocode(city);
        } catch (error) {
          console.log('地理编码失败');
        }
      }

      // 如果都没有，尝试IP定位
      if (!locationInfo) {
        try {
          const ip = ctx.request.ip || ctx.ip;
          locationInfo = await service.location.getLocationByIP(ip);
        } catch (error) {
          console.log('IP定位失败，使用默认位置');
          locationInfo = service.location.getDefaultLocation();
        }
      }

      const recommendations = await service.recommendation.getTodayRecommendations(userId, locationInfo);

      ctx.body = {
        code: 200,
        message: '获取今日推荐成功',
        data: recommendations
      };
    } catch (error) {
      console.error('获取今日推荐失败:', error);
      ctx.throw(500, '获取今日推荐失败，请稍后重试');
    }
  }

  // 基于天气的搭配推荐
  async weatherBased() {
    const { ctx, service } = this;



    try {
      const { weather, temperature, location } = ctx.query;
      
      if (!weather || !temperature) {
        ctx.throw(400, '缺少天气信息');
      }

      const recommendations = await service.recommendation.getWeatherBasedRecommendations(
        ctx.state.user?.id || 1,
        { weather, temperature: parseFloat(temperature), location }
      );

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: recommendations,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 基于场合的搭配推荐
  async occasionBased() {
    const { ctx, service } = this;



    try {
      const { occasion, style } = ctx.query;
      
      if (!occasion) {
        ctx.throw(400, '缺少场合信息');
      }

      const recommendations = await service.recommendation.getOccasionBasedRecommendations(
        ctx.state.user?.id || 1,
        { occasion, style }
      );

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: recommendations,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 基于颜色搭配的推荐
  async colorBased() {
    const { ctx, service } = this;



    try {
      const { baseColor, colorScheme } = ctx.query;
      
      if (!baseColor) {
        ctx.throw(400, '缺少基础颜色');
      }

      const recommendations = await service.recommendation.getColorBasedRecommendations(
        ctx.state.user?.id || 1,
        { baseColor, colorScheme }
      );

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: recommendations,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 基于个人偏好的推荐
  async personalBased() {
    const { ctx, service } = this;



    try {
      const recommendations = await service.recommendation.getPersonalBasedRecommendations(
        ctx.state.user?.id || 1
      );

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: recommendations,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 基于相似用户的推荐
  async similarUserBased() {
    const { ctx, service } = this;



    try {
      const recommendations = await service.recommendation.getSimilarUserBasedRecommendations(
        ctx.state.user?.id || 1
      );

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: recommendations,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 智能搭配建议
  async smartOutfit() {
    const { ctx, service } = this;



    try {
      const { clothingIds, occasion, weather } = ctx.request.body;
      
      if (!clothingIds || !Array.isArray(clothingIds) || clothingIds.length === 0) {
        ctx.throw(400, '请选择至少一件衣服');
      }

      const suggestions = await service.recommendation.getSmartOutfitSuggestions(
        ctx.state.user?.id || 1,
        { clothingIds, occasion, weather }
      );

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: suggestions,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取今日推荐
  async dailyRecommendation() {
    const { ctx, service } = this;



    try {
      const recommendations = await service.recommendation.getDailyRecommendations(
        ctx.state.user?.id || 1
      );

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: recommendations,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 记录推荐反馈
  async recordFeedback() {
    const { ctx, service } = this;



    try {
      const { recommendationId, feedback, rating } = ctx.request.body;
      
      if (!recommendationId || !feedback) {
        ctx.throw(400, '缺少必要参数');
      }

      await service.recommendation.recordFeedback(
        ctx.state.user?.id || 1,
        { recommendationId, feedback, rating }
      );

      ctx.body = {
        code: 200,
        message: '反馈记录成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }
}

module.exports = RecommendationController;
